﻿function LoadNewsfeed(staffId, appType, appId, numOfPosts, commentLimitedLength, DOMContainer) {

    $.ajax({
        beforeSend: function () {
            $("#loadingContainer").show();
        },
        type: "Get",
        contentType: "application/json; charset=utf-8",
        dataType: 'jsonp',
        cache: false,
        url: newsfeedSvcUrl + "GetFeedPost?staffId=" + staffId + "&appType=" + appType + "&appId=" + appId + "&pageNum=" + numOfPosts + "&excludePostId=",
        success: function (feedPostData) {
            //display Newsfeed
            var feedPostJsonp = eval('(' + feedPostData + ')');
            if (feedPostJsonp.length != 0) {
                $("#newsfeedTemplate").tmpl(feedPostJsonp).appendTo(DOMContainer);

                //to improve performace
                $.each(feedPostJsonp, function (i, item) {
                    $("#feedpost_" + item.id).hide();
                    $("#feedpost_" + item.id).show(0);
                });

                $("#curBiggestId").val(feedPostJsonp[0].maxId);
                setTimeout(function () {
                    $.each(feedPostJsonp, function (a, b) {
                        $("#feedPostIdCollect").val($("#feedPostIdCollect").val() + b.id + "|");
                        loadPostComment(staffId, b.id, commentLimitedLength);
                    });
                }, 1);
                if (feedPostJsonp[0].postCount < 30) {
                    $("#loadMoreFeed").hide();
                } else {
                    $("#loadMoreFeed").show();
                }
            }
        },
        error: function (a, b, c) { alert(a + "__" + b + "__" + c); },
        complete: function (a, b) {
            $("#loadingContainer").hide();
            //after load newsfeed need set interval to load comments
            //test.
            loadCommentByInterval(staffId, commentLimitedLength);
            AutoLoadNewsfeedbyInterval(staffId, appType, appId, 25, commentLimitedLength, DOMContainer);

        }
    });
}

function loadPostComment(staffId, feedPostId, commentLimitedLength) {
    LoadFeedCommentByFeedPostId(feedPostId, commentLimitedLength);
}

function LoadFeedCommentByFeedPostId(feedPostId, commentLimitedLength) {
    $.ajax({
        type: "Get",
        contentType: "application/json; charset=utf-8",
        dataType: 'jsonp',
        cache: false,
        url: newsfeedSvcUrl + "GetPostComment?feedPostId=" + feedPostId,
        success: function (commentData) {
            var commentJsonp = eval('(' + commentData + ')');
            //alert(commentJsonp[0].actualCount);
            if (commentJsonp[0] != undefined) {
                //$("#moreCommentList_" + feedPostId).html("");
                $("#commentCount_" + commentJsonp[0].postId).val(commentJsonp[0].actualCount);
                $("#moreCommentTemplate").tmpl(commentJsonp[0]).appendTo("#moreCommentList_" + feedPostId);
                $("#divCommentCount_" + feedPostId).text($("#commentCount_" + commentJsonp[0].postId).val());
            }

            $.each(commentJsonp, function (i, item) {
                ClipCommentLength(commentJsonp, i, commentLimitedLength);
            });
            //$("#commentList_" + feedPostId).html("");
            $("#commentTemplate").tmpl(commentJsonp).appendTo("#commentList_" + feedPostId);

        },
        error: function (a, b, c) { }
    });
}

function ClipCommentLength(feedCommentJsonp, index, commentLimitedLength) {

    feedCommentJsonp[index].showMoreLink = 'false';
    if (feedCommentJsonp[index].content.length > parseInt(commentLimitedLength)) {
        feedCommentJsonp[index].moreContent = feedCommentJsonp[index].content.substr(commentLimitedLength);
        feedCommentJsonp[index].showMoreLink = 'true';
        feedCommentJsonp[index].content = feedCommentJsonp[index].content.substring(0, commentLimitedLength);
    }
}

function loadCommentByInterval(staffId, commentlimitedLength) {

    setInterval(function () {
        $.each($(".hiddenCss"), function (i, item) {
            var postId = $(item).attr("id").split("_")[1];
            var lastestUpdatedTime = $(item).val();
            $.ajax({
                type: "Get",
                contentType: "application/json; charset=utf-8",
                dataType: 'jsonp',
                cache: false,
                url: newsfeedSvcUrl + 'GetFeedPostLastestUpdateTime?feedPostId=' + postId,
                success: function (dataRet) {
                    // if not match means comments have been changed
                    if (dataRet != lastestUpdatedTime) {
                        loadAllComments(postId, commentlimitedLength, false);
                    }
                }
            });
        });
    }, 30000);    //every 30 sceconds will check is there any new comment to the post
}

function loadAllComments(postId, commentLimitedLength, expandAll) {

    $.ajax({
        type: "Get",
        contentType: "application/json; charset=utf-8",
        dataType: 'jsonp',
        cache: false,
        url: newsfeedSvcUrl + "GetMoreCommentByFeedpost?feedpostId=" + postId,
        success: function (commentData) {
            var commentJsonp = eval('(' + commentData + ')');
            if (commentJsonp[0] != undefined) {
                //alert(commentJsonp);
                $("#commentCount_" + postId).val(commentJsonp[0].actualCount);
                $("#moreCommentList_" + postId).empty();
                $("#moreCommentTemplate").tmpl(commentJsonp[0]).appendTo("#moreCommentList_" + postId);
                $("#divCommentCount_" + postId).text($("#commentCount_" + postId).val());
                $.each(commentJsonp, function (i, item) {
                    ClipCommentLength(commentJsonp, i, commentLimitedLength);
                });
                $("#commentList_" + postId).empty();
                $("#commentTemplate").tmpl(commentJsonp).appendTo("#commentList_" + postId);
                //hide all comments except top 3 then show animation
                hideIndex = $("#commentList_" + postId).children(".feedComment").length - 3;
                $("#commentList_" + postId).children(".feedComment:lt(" + hideIndex + ")").hide();

                if (expandAll) {
                    //after load will show all the comments with animation
                    slideDownAnimation($("#commentList_" + postId), $("#commentList_" + postId).children(".feedComment").length - 1);
                    $("#slideStatus_" + postId).val("down"); //change status
                    $("#slideStatus_" + postId).siblings(".commentDesc").text("所有评论");
                }
            }
        },
        error: function (a, b, c) { }
    });
}

function AutoLoadNewsfeedbyInterval(staffId, appType, appId, numOfPosts, commentLimitedLength, DOMContainer) {
    setInterval(function () {
        AutoGetNewsfeed(staffId, appType, appId, numOfPosts, commentLimitedLength, DOMContainer);
    }, 30000);
}

function AutoGetNewsfeed(staffId, appType, appId, numOfPosts, commentLimitedLength, DOMContainer) {

    var biggestId = $("#curBiggestId").val();
    var excludeIds = $("#feedPostIdCollect").val();
    $.ajax({
        //        beforeSend: function () {
        //            //   $("#loadingContainer").show();
        //        },
        type: "Get",
        contentType: "application/json; charset=utf-8",
        dataType: 'jsonp',
        cache: false,
        url: newsfeedSvcUrl + "GetFeedPost?staffId=" + staffId + "&appType=" + appType + "&appId=" + appId + "&pageNum=" + numOfPosts + "&excludePostId=" + excludeIds,
        success: function (feedPostData) {
            //display Newsfeed
            var feedPostJsonp = eval('(' + feedPostData + ')');
            if (feedPostJsonp.length != 0) {
                $("#newsfeedTemplate").tmpl(feedPostJsonp).prependTo(DOMContainer);

                //to improve performace
                $.each(feedPostJsonp, function (i, item) {
                    $("#feedpost_" + item.id).hide();
                    $("#feedpost_" + item.id).show(0);
                });

                $("#curBiggestId").val(feedPostJsonp[0].maxId);

                setTimeout(function () {
                    $.each(feedPostJsonp, function (a, b) {
                        $("#feedPostIdCollect").val($("#feedPostIdCollect").val() + b.id + "|");
                        loadPostComment(staffId, b.id, commentLimitedLength);
                    });
                }, 1);
                if (feedPostJsonp[0].postCount < 30) {
                    $("#loadMoreFeed").hide();
                } else {
                    $("#loadMoreFeed").show();
                }
            }
        },
        error: function (a, b, c) { },
        complete: function (a, b) {
        }
    });
}
function slideDownAnimation(CommentContainer, index) {
    var childLength = CommentContainer.children(".feedComment").length;

    if (index >= 0) {
        if (index < childLength - 3) {
            $(CommentContainer.children(".feedComment")[index]).slideDown(0, function () { slideDownAnimation(CommentContainer, index - 1); });
        }
        else {
            slideDownAnimation(CommentContainer, index - 1);
        }
    }
}

///======================
//staffId --current login staff
//appType --current page area i.e :header page , workgroup page, committee page or personal page.
//appId -- type id header page is 0, personal page is staffid, workgroup is workgroup id ....
//commentLimitedLength --comment string length
//feedPostGrowthNum  --when click more when load how many nums of feedpost
//maxFeedPostCount  --max number feedpost allow to load
function RegisterEvent(staffId, appType, appId, commentLimitedLength, feedPostGrowthNum, maxFeedPostCount) {

    $(".moreFeedComment").live("click", function () {
        var commentContainer = $(this).siblings("span");
        var curComment = commentContainer.text();
        var finalStr = curComment + $(this).attr("moreContent");
        $(this).attr("moreContent", "");
        commentContainer.text("");
        commentContainer.text(finalStr);
        $(this).hide();
    });

    $(".newsfeedInput").focus(function () {
        $(this).val("");
        $(".newsfeedSubmit").show();
    });

    $(".comment").live("click", function () {

        var postId = $("#HiddenCommentPostId").val();
        if (postId != '') {
            $("#newFeedcomment_" + postId).siblings(".newFeedcommentInput").val("");
            $("#newFeedcomment_" + postId).fadeOut("slow", function () {
            });
        }
        var currentPostId = $(this).parent().parent().parent().attr("id").split('_')[1];
        $("#HiddenCommentPostId").val(currentPostId);

        $(this).parent().parent().siblings(".newFeedcomment").show();
        var newsFeedCommentInput = $(this).parent().parent().siblings(".newFeedcomment").children(".newFeedCommentContent").children(".newFeedcommentInput");

        newsFeedCommentInput.height(50);
        newsFeedCommentInput.addClass("commentAreaBorder");
        newsFeedCommentInput.val("").focus();
    });

    $(".newsfeedSubmit").click(function () {

        SubmitNewsfeed(staffId, appType, appId);
        $(".newsfeedInput").val("你想谈论...");
    });

    $(".newFeedcommentInput").live("keydown", function (event) {
        if (event.which == 13) {
            $(this).siblings().click();
            return false;
        }
    });

    $(".newFeedcommentInput").live("click", function () {
        $(this).height(50);
        $(this).addClass("commentAreaBorder");
        if ($(this).val() == "请输入...")
            $(this).val("");
    });

    $(".newsfeedInput").keydown(function (event) {
        if (event.which == 13) {
            SubmitNewsfeed(staffId, appType, appId);
            $(".newsfeedInput").val("");
            return false;
        }
    });

    $(".setThirty").live("click", function () {
        var postId = $(this).parent().parent().attr("id").split('_')[1];
        var span = $(this).children(".commentDesc");
        //if did not load all comments so load , only load once during the page lifecycle
        if ($("#commentList_" + postId).children(".feedComment").length < parseInt($("#commentCount_" + postId).val())) {
            loadAllComments(postId, commentLimitedLength, true);
        }
        else {
            if ($("#slideStatus_" + postId).val() == "up") {
                slideDownAnimation($("#commentList_" + postId), $("#commentList_" + postId).children(".feedComment").length - 1);
                $("#slideStatus_" + postId).val("down");
                span.text("所有评论");
            }
            else {
                slideUpAnimation($("#commentList_" + postId), 0);
                $("#slideStatus_" + postId).val("up");
                span.text("显示所有评论");
            }
        }
    });

    submitComment(staffId, commentLimitedLength);

    DeleteComment(staffId, commentLimitedLength);

    DeleteFeedPost(staffId);

    $("#loadMoreFeed").live("click", function () {

        $(this).html("<img src='/_layouts/JM.JCY.Resource/images/loading.gif' />");
        $(this).css("background-color", "white");

        //load when less than maxLength
        var curFeedPostCount = $("#newsfeedList").children(".newsfeedPost").length;
        if (curFeedPostCount < maxFeedPostCount) {
            //if (smallIdOnPage != 0) {
            $.ajax({
                type: "Get",
                dataType: "jsonp",
                cache: false,
                url: newsfeedSvcUrl + "GetMoreFeedPost?staffId=" + staffId + "&appType=" + appType + "&appId=" + appId + "&excludePostId=" + $("#feedPostIdCollect").val(), //every time only load 5 records
                success: function (feedPostData) {
                    //display Newsfeed
                    var feedPostJsonp = eval('(' + feedPostData + ')');

                    if (feedPostJsonp.length != 0) {
                        $("#curBiggestId").val(feedPostJsonp[0].maxId);

                        $("#newsfeedTemplate").tmpl(feedPostJsonp).appendTo("#newsfeedList");

                        //to improve performace
                        $.each(feedPostJsonp, function (i, item) {

                            $("#feedpost_" + item.id).hide();

                            $("#feedpost_" + item.id).show(0);

                        });

                        setTimeout(function () {
                            $.each(feedPostJsonp, function (a, b) {
                                $("#feedPostIdCollect").val($("#feedPostIdCollect").val() + b.id + "|");
                                loadPostComment(staffId, b.id, commentLimitedLength);
                            });
                        }, 100);
                    }

                },
                error: function (a, b, c) { },
                complete: function (a, b) {
                }
            });
        }

        $(this).fadeOut(0, function () {
            $(this).text("查看更多");
            $(this).css("background-color", "#FAFAFA");
            $(this).fadeIn(0);
        });
    });
}


function slideUpAnimation(CommentContainer, index) {
    var childLength = CommentContainer.children(".feedComment").length;
    if (index < childLength - 1) {
        if (index < childLength - 3) {
            $(CommentContainer.children(".feedComment")[index]).slideUp(0, function () { slideUpAnimation(CommentContainer, index + 1); });
        }
        else {
            slideUpAnimation(CommentContainer, index + 1);
        }
    }
}

function submitComment(staffId, commentLimitedLength) {

    $(".commentSubmit").live("click", function () {
        var feedPostId = $(this).parent().parent().attr("id").split('_')[1];
        var commentStr = $(this).siblings(".newFeedcommentInput").val();
        if (commentStr.trim() != '') {
            $.ajax({
                //InsertComment(int staffId, int feedPostId, string content)
                type: "Get",
                contentType: "application/json; charset=utf-8",
                dataType: 'jsonp',
                cache: false,
                url: newsfeedSvcUrl + "InsertComment?staffId=" + staffId + "&feedPostId=" + feedPostId + "&content=" + escape(commentStr),
                success: function (commentData) {
                    commentJsonp = eval(commentData);
                    ClipCommentLength(commentJsonp, 0, commentLimitedLength);

                    $("#commentTemplate").tmpl(commentJsonp).appendTo("#commentList_" + feedPostId);

                    $("#feedComment_" + commentJsonp[0].commentId).hide();
                    $("#feedComment_" + commentJsonp[0].commentId).slideDown(0);

                    $("#commentCount_" + feedPostId).val(commentJsonp[0].actualCount);

                    if (commentJsonp[0].actualCount > 3) {
                        if ($("#moreCommentList_" + feedPostId).text() != "") {
                            $("#moreComments_" + feedPostId).remove();
                        }
                        $("#moreCommentTemplate").tmpl(commentJsonp).appendTo("#moreCommentList_" + feedPostId);

                        $("#divCommentCount_" + feedPostId).text(commentJsonp[0].actualCount);
                    }

                    //  showCommentAnimation($("#commentList_" + feedPostId));
                    slideUpAnimation($("#commentList_" + feedPostId), 0);
                    $(".newFeedcommentInput").val("");
                    //$(".newFeedcomment").fadeOut("slow");
                    $(".newFeedcomment").slideUp(0);
                    //to move the comment container
                    if ($("#feedpost_" + feedPostId).index() != 0) {
                        $("#feedpost_" + feedPostId).prependTo("#newsfeedList");
                    }
                }
            });
        }
    });
}

function DeleteComment(staffId, commentLimitedLength) {
    $(".deleteComment").live("click",
       function () {
           var commentCtrl = $(this);
           $("#newsfeed-confirm").text("你真的要删除这个评论吗？");
           $("#newsfeed-confirm").dialog({
               resizable: false,
               height: 150,
               title: '操作确认',
               modal: true,
               buttons: {

                   "确定": function () {
                       var ctrlId = commentCtrl.attr("id");
                       var commentId = ctrlId.split("_")[1];
                       var container = commentCtrl.parent().parent().parent();
                       container.hide(0, function () {
                           //after hide should delete the comment from database

                           $.ajax({
                               type: "Get",
                               contentType: "application/json; charset=utf-8",
                               dataType: 'jsonp',
                               cache: false,
                               url: newsfeedSvcUrl + "DeleteComment?CommentId=" + commentId,
                               success: function () {

                                   var commentListContainer = container.parent();
                                   var feedPostId = commentListContainer.attr("id").split('_')[1];
                                   var commentLength = $("#commentCount_" + feedPostId).val();
                                   if ($("#slideStatus_" + feedPostId).val() == "up" && commentListContainer.children(".feedComment").length == commentLength) {
                                       //show the next comment to keep 3 comments per feedPost
                                       var showIndex = commentLength - 4;
                                       commentListContainer.children(".feedComment:eq(" + showIndex + ")").show("slow");
                                   }
                                   else if (commentListContainer.children(".feedComment").length < commentLength) {
                                       loadAllComments(feedPostId, commentLimitedLength, false);
                                   }

                                   //reset the count on page not through server
                                   $("#commentCount_" + feedPostId).val($("#commentCount_" + feedPostId).val() - 1);
                                   $("#divCommentCount_" + feedPostId).text($("#commentCount_" + feedPostId).val());
                                   if ($("#commentCount_" + feedPostId).val() <= 3) {
                                       $("#moreComments_" + feedPostId).hide(0, function () { $(this).remove(); });
                                       $("#moreCommentList_" + feedPostId).hide();
                                   }
                                   container.remove();
                               }
                           });
                       });

                       $(this).dialog("close");
                   },
                   "取消": function () {
                       $(this).dialog("close");
                   }

               }
           });
       });
}

function DeleteFeedPost(staffId) {
    $(".deleteFeedpost").live("click", function () {
        var feedPostId = $(this).attr("id").split('_')[1];

        $("#newsfeed-confirm").text("你真的要删除这个话题和其所有评论吗?");

        $("#newsfeed-confirm").dialog({
            resizable: false,
            height: 150,
            title: '操作确认',
            modal: true,
            buttons: {
                "确定": function () {
                    $.ajax({
                        type: "GET",
                        dataType: 'jsonp',
                        cache: false,
                        contentType: "application/json; charset=utf-8",
                        cache: false,
                        url: newsfeedSvcUrl + "DeleteFeedPost?feedpostId=" + feedPostId,
                        success: function () {
                            $("#feedpost_" + feedPostId).hide(0);

                            $("#feedPostIdCollect").val($("#feedPostIdCollect").val().replace(feedPostId + "|", ""));
                        }
                    });
                    $(this).dialog("close");
                },
                "取消": function () {
                    $(this).dialog("close");
                }
            }
        });
    });
}

function SubmitNewsfeed(staffId, appType, appId) {
    postContent = $(".newsfeedInput").val();

    if (postContent.trim() != '' && postContent != "你想谈论...") {
        $.ajax({
            type: "GET",
            dataType: 'jsonp',
            contentType: "application/json; charset=utf-8", //utf-8 format for IE7
            cache: false,
            url: newsfeedSvcUrl + "InsertFeedPost?staffId=" + staffId + "&postContent=" + escape(postContent) + "&appType=" + appType + "&appId=" + appId,
            success: function (feedData) {
                var feedJsonp = eval(feedData);

                //when add a new newsfeed, record these new feedPost Id
                $("#newFeedPostIdCollect").val($("#newFeedPostIdCollect").val() + feedJsonp[0].id + "|");

                $("#feedPostIdCollect").val($("#feedPostIdCollect").val() + feedJsonp[0].id + "|");

                $("#newsfeedTemplate").tmpl(feedJsonp).prependTo("#newsfeedList");

                //to improve performace

                $("#feedpost_" + feedJsonp[0].id).hide();

                $("#feedpost_" + feedJsonp[0].id).show(0);
            }
        });
    }
}